// import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    openid:'',
    tenant_access_token:'',
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_OPENID: (state, openid) => {
    state.openid = openid
  },
  SET_tenant_access_token: (state, tenant_access_token) => {
    state.tenant_access_token = tenant_access_token
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // login({ username: username.trim(), password: password }).then(response => {
        const data = {
          token: 'admin-token',
        }
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // get user info
  getInfo({ commit, state }, userInfo) {
    return new Promise((resolve, reject) => {
      // getInfo(state.token).then(response => {
        console.log('getInfo ',commit, state,userInfo)
        const data = {
          roles: ['admin'],
          introduction: 'I am a super administrator',
          // 头像
          avatar: userInfo.figureurl,
          // 名称
          name: userInfo.nickname
        }
        console.log('Info ',data)
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, avatar } = data
        console.log('登录用户 ',userInfo.nickname,userInfo.figureurl)
        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_OPENID', userInfo.openId)
        commit('SET_TOKEN', 'admin-token')
        resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
        // QC.Login.signOut()
        // this.$message.info('qq退出登录')
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

